package com.ydzt.fanka.server.space.transmit;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.persistence.BufferStore;
import com.ydzt.fanka.server.utils.IOUtil;
import com.ydzt.fanka.server.utils.NetUtil;

/*
 * 此线程将读取wait_transmit文件夹中的报文将报文发送给中心
 * */
public class SendTransmitServer extends Thread{
	static Logger logger = Logger.getLogger(SendTransmitServer.class.getName());
	public void run(){
		while(true){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			File f = new File(InitData.wait_transmitPath);
			if(f != null){
				int count = f.listFiles().length;
				if(count > 0){
					logger.info("wait_transmit文件夹中 未发送报文有  " + count + "  个");
				}
				if(count != 0){
					try {
						File currentFile = f.listFiles()[0];
						//读取wait_transmit文件夹中的报文
						byte[] pkg = IOUtil.toByteArrayTraditional(currentFile.getAbsolutePath());
						if(pkg.length != 0){
							//将读取的报文发送到中心
							if(0 == NetUtil.synSendMsg(pkg)){
								if(BufferStore.writePackageIntoBackupTransmit(pkg)){
									currentFile.delete();
								}
							}
						}
						else{
							logger.error("发现wait_transmit中有长度为0的坏包");
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				else{
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
